
package node;

import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import message.Message;

/**
 * The ability to Retrieve data in a ring.
 * 
 * @author TCSS 558 Team 6
 * @version Spring 2013
 * 
 */

public class NodeGet
{

  /**
   * The node .
   */
  private static Node my_node;

  /**
   * 
   * @param the_registry .
   * @throws AccessException
   * @throws RemoteException
   */
  public static void isSettled(final Registry the_registry) throws AccessException,
      RemoteException
  {
    final String[] registered_nodes = the_registry.list();
    if (registered_nodes.length != 0)
    {
      System.out.println("The system is ready");
    }
  }

  /**
   * @param args
   */
  public static void main(String[] the_args)
  {

    int node_id = Integer.parseInt(the_args[4]);
    
    
    final String host = the_args[0];
    final int port = Integer.parseInt(the_args[1]);
    final String registry_name = the_args[2];
    try
    {
      final Registry bootstrap = LocateRegistry.getRegistry(host, port);
      final Registry registry = (Registry) bootstrap.lookup(registry_name);
      // checks if the system is set up.
      isSettled(registry);

      // my_node = new ActualNode(node_id, m_value, registry);
      my_node = (Node) registry.lookup("node_id_" + node_id);

      System.out.println("start");

      System.out.println("getting key = " + the_args[3]);

      int nodeid = my_node.getMyID();
      System.out.println("node id being tested: " + nodeid);

      // hashes the key and gets the the destination;
      int hash = the_args[3].hashCode();
      if (hash < 0)
      {
        hash *= -1;
      }
      int destination = hash % (1 << 3);
      System.out.println("the hashed node id this key will go to: " + destination);

     

      Message response = (Message) my_node.get(the_args[3]);

      System.out.println("this came back from the network: " + response.getValue());

    }
    catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (NotBoundException e)
    {
      
      e.printStackTrace();
    }
  }

}
